var changedNodes = 0
var tableIn = null;
var table = null;
var form = null;
var curriculumOriginalPrice1 = null
var curriculumName1 = null
var curriculumClassificationid =null
var uid = localStorage.getItem("uid")

$("#back").click(function (){
    window.history.back();
})
function log(operation){
    $.ajax({
        url : "/curriculum/intermediate/addOperationLog",
        dataType : 'json',
        type : 'post',
        data :{"logUserId":uid,"logList":"课程列表","logOperation":operation},
        success : function(res) {

        },
        errorfun : function() {

        }
    });
}
$("#count").click(function () {
    table.reload('curriculum',{

        where:{

        }
    })
    log("全部查看")

})
$("#chongzhi").click(function (){
    location.reload();
})
$("#grounding").click(function () {
    table.reload('curriculum',{

        where:{
            curriculumShelves:0
        }
    })
    log("查看已上架")
})
$("#onShelf").click(function () {
    table.reload('curriculum',{

        where:{
            curriculumShelves:1
        }
    })
    log("查看未上架")
})
$("#Reviewed").click(function () {
    table.reload('curriculum',{

        where:{
            curriculumToExamine:0
        }
    })
    log("查看待审核")
})
$("#Failed").click(function () {
    table.reload('curriculum',{

        where:{
            curriculumToExamine:2
        }
    })
    log("查看未审核")
})
function zTreeOnCheck(event, treeId, treeNode) {
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    changedNodes = zTree.getChangeCheckedNodes();
    for ( var i=0 ; i < changedNodes.length ; i++ ){
        treeNode1 = changedNodes[i];
    }

};
function aaa(curriculumId){
    layer.open({
        type:2,
        title:'审核详情',
        content: "../../../pages/course/courseManagement/enrymsg/curriculumexaminelog.html",
        shade: 0,
        offset: ['50%', '50%'],
        area:['35%','35%'],
        success:function(layero,index) {
            var boby = layer.getChildFrame('body,index');
            // boby.find("input[name=curriculumId]").attr("value",curriculumId);
            var iframeWin = window[layero.find('iframe')[0]['name']];//得到iframe页的窗口对象，执行iframe页的方法：
            console.log(curriculumId)
            iframeWin.bbb(curriculumId);
            // iframeWin.ccc(curriculumId);
        }
    })
    log("查看审核详情")

}
function zTreeOnClick(treeId, treeNode,event) {
     var val = event.classificationId
        console.log(val)
    table.reload('curriculum',{

        where:{
            curriculumClassificationid:val
        }
    })
    log("查看分类")
};
$("input[name='curriculumOriginalPrice']").blur(function () {
    var val = $(this).val();
    curriculumOriginalPrice1 = val
    table.reload('curriculum',{

        where:{
            curriculumOriginalPrice:val
        }
    })
});
$("input[name='curriculumName']").blur(function () {

    var val = $(this).val();
    curriculumName1 = val;
    table.reload('curriculum',{

        where:{
            curriculumName:val
        }
    })
});
$("#query").click(function (){
    table.reload('curriculum',{

        where:{
            curriculumName:curriculumName1,
            curriculumOriginalPrice:curriculumOriginalPrice1,
            curriculumClassificationid:curriculumClassificationid
        }
    })
    log("普通查询")
})
function abvancedQuery(data){
    table.reload('curriculum',{

        where:{
            curriculumName:data.curriculumName,
            curriculumOriginalPrice:data.curriculumOriginalPrice,
            curriculumClassificationid:data.curriculumClassificationid,
            curriculumShelves:data.curriculumShelves,
            curriculumToExamine:data.curriculumToExamine,
            currculumCreatedBy:data.currculumCreatedBy
        }
    })
    log("高级查询")
}
$("#advancedQuery").click(function (){
    layer.open({
        type: 2,
        content: '../../../pages/course/courseManagement/enrymsg/advancedQuery.html',
        title:"高级搜索",
        area: ['50%', '50%']
    });
})
function refresh(){
    tableIn.reload("curriculum");
}
layui.use(['table','form'], function(){
     table = layui.table;
     form = layui.form;
    //第一个实例
    tableIn = table.render({
        elem: '#demo'
        ,id:"curriculum"

        ,height: 600
        ,url: '/curriculum/primary/getAllCm' //数据接口
        ,page: true //开启分页
        ,cols: [[ //表头
            {field: 'curriculumId', title: '编号', width:80, sort: true, fixed: 'left'}
            ,{field: 'curriculumPictureurl', title: '商品图片', width:135,height: 100,
                templet:function (d) { return '<div><img src="'+d.curriculumPictureurl+'", ' +
                    'style="width: 200px;height: 100px"></div>'}}
            ,{field: 'curriculumName', title: '课程名称', width:135}
            ,{field: 'currculumCreatedBy', title: '上传人', width:80}
            ,{field: 'curriculumDetails', title: '备注', width: 100}
            ,{field: 'curriculumOriginalPrice', title: '价格', width: 80}
            ,{field: 'curriculumShelves', title: '状态', width: 100, sort: true,templet: '#switchTpl'}
            ,{field: 'classificationName', title: '分类', width: 80}
            ,{field: 'currculumSalesVolumes', title: '销量', width: 135}
            ,{field: 'curriculumToExamine', title: '审核状态', width: 135,templet: function (d) {
                    if (d.curriculumToExamine == 0){
                        return "未审核"
                    }else if(d.curriculumToExamine == 1) {
                        return '<div style="line-height: 10px;margin-left: 10px;margin-right: 0px;margin-top: 20px;padding: 0">' +
                            '<p>已审核</p><br><br><br><a onclick="aaa('+d.curriculumId+')">审核详情</a></div>'
                    }else if(d.curriculumToExamine == 2){
                        return '<div style="line-height: 10px;margin-left: 10px;margin-right: 0px;margin-top: 20px;padding: 0">' +
                            '<p>未通过</p><br><br><br><a onclick="aaa('+d.curriculumId+')">审核详情</a></div>'}
                }},
            {fixed: 'right',title: '操作', width: 150, align:'center', toolbar: '#toolDemo'}
        ]],toolbar: '#toolbarDemo'
    });
    table.on('toolbar(test)', function(obj){

        if(obj.event == 'add'){
            if(changedNodes == ''){
                alert('请选择课程的分类');
            }else if(changedNodes.length > 1 ){
                layer.msg('不能选择多个分类')
            }else{
                console.log(changedNodes[0].classificationId);
                console.log(changedNodes)
                layer.open({
                    type:2,
                    title:'添加',
                    content: "../../../pages/course/courseManagement/enrymsg/addcurriculum.html",
                    area:['80%','80%'],
                    success:function(layero,index){

                        var boby = layer.getChildFrame('body,index');
                        boby.find("input[name = curriculumClassificationid]").val(changedNodes[0].classificationId);
                        boby.find("input[name = currculumCreatedBy]").val(uname);
                        boby.find("input[name = curriculumUserid]").val(uid);
                        boby.find("#classificationName").val(changedNodes[0].classificationName);
                        log("添加课程");
                    }
                })


            }
        }
    });
    form.on('switch(sexDemo)', function(data){
        console.log(data.value); //开关value值，也可以通过data.elem.value得到
        $.ajax({
            url : "/curriculum/intermediate/updateOnShelfStatus",
            dataType : 'json',
            type : 'post',
            data :{"curriculumId":data.value,"currculumUpdatedBy":uname},
            success : function(res) {
                log("修改上架状态")
            },
            errorfun : function() {

            }
        });

    });
    table.on('tool(test)', function(obj){
        switch(obj.event){
            case 'see':

                layer.open({
                    type:2,
                    title:'查看详情信息',
                    content: "../../../pages/course/courseManagement/enrymsg/viewDetails.html",
                    area:['80%','80%'],
                    success:function(layero,index) {
                        var boby = layer.getChildFrame('body,index');
                        boby.find("td[name = curriculumName]").text(obj.data.curriculumName);
                        boby.find("td[name = currculumCreationTime]").text(obj.data.currculumCreationTime);
                        boby.find("td[name = currculumCreatedBy]").text(obj.data.currculumCreatedBy);
                        boby.find("td[name = curriculumOriginalPrice]").text(obj.data.curriculumOriginalPrice);
                        boby.find("td[name = curriculumKeyWord]").text(obj.data.curriculumKeyWord);
                        boby.find("td[name = classificationName]").text(obj.data.classificationName);
                        boby.find("td[name = currculumLikes]").text(obj.data.currculumLikes);
                        boby.find("td[name = currculumCollectionQuantity]").text(obj.data.currculumCollectionQuantity);
                        boby.find("td[name = currculumCommentVolume]").text(obj.data.currculumCommentVolume);
                        boby.find("td[name = curriculumSynopsis]").text(obj.data.curriculumSynopsis);
                        boby.find("td[name = curriculumPictureurl]").html('<div><img src="'+obj.data.curriculumPictureurl+'", ' +
                            'style="width: 200px;height: 100px"></div>');
                        boby.find("td[name = curriculumUrl]").html('<div><video src="'+obj.data.curriculumUrl+'"style="width: 800px;height: 600px" controls></video> </div>');


                    }
                })
                log("查看详情信息")
                break;
            case 'edit':
                layer.open({
                    type:2,
                    title:'日志',
                    content: "../../../pages/course/courseManagement/enrymsg/courselog.html",
                    area:['80%','80%'],
                    success:function(layero,index) {
                        var boby = layer.getChildFrame('body,index');
                        var iframeWin = window[layero.find('iframe')[0]['name']];//得到iframe页的窗口对象，执行iframe页的方法：
                        console.log(obj.data.curriculumId);
                        iframeWin.bbb(obj.data.curriculumId);
                    }
                })
                log("查看课程日志")

                break;
            case 'delete':
                $.ajax({
                    url : "/curriculum/intermediate/delete",
                    dataType : 'json',
                    type : 'post',
                    data :{"curriculumId":obj.data.curriculumId},
                    success : function(res) {
                        refresh();
                        log("删除课程");
                    },
                    errorfun : function() {

                    }
                });

                break;
            case 'update':
                layer.open({
                    type:2,
                    title:'修改信息',
                    content: "../../../pages/course/courseManagement/enrymsg/editInformation.html",
                    area:['80%','80%'],
                    success:function(layero,index) {
                        var boby = layer.getChildFrame('body,index');
                        boby.find("input[name = curriculumId]").val(''+obj.data.curriculumId+'');
                        boby.find("td[name = curriculumName]").html('<div><input type="text" name="curriculumName" value='+obj.data.curriculumName+'></div>');
                        boby.find("td[name = currculumCreationTime]").html('<div><input type="text" name="currculumCreationTime" value='+obj.data.currculumCreationTime+'></div>');
                        boby.find("td[name = currculumCreatedBy]").html('<div><input type="text" name="currculumCreatedBy" value='+obj.data.currculumCreatedBy+'></div>');
                        boby.find("td[name = curriculumOriginalPrice]").html('<div><input type="text" name="curriculumPresentPrice" value='+obj.data.curriculumOriginalPrice+'></div>');
                        boby.find("td[name = curriculumKeyWord]").html('<div><input type="text" name="curriculumKeyWord" value='+obj.data.curriculumKeyWord+'></div>');
                        boby.find("td[name = classificationName]").html('<div><input type="text" name="classificationName" value='+obj.data.classificationName+'></div>');
                        boby.find("td[name = currculumLikes]").html('<div><input type="text" name="currculumLikes" value='+obj.data.currculumLikes+'></div>');
                        boby.find("td[name = currculumCollectionQuantity]").html('<div><input name="currculumCollectionQuantity" type="text" value='+obj.data.currculumCollectionQuantity+'></div>');
                        boby.find("td[name = currculumCommentVolume]").html('<div><input type="text" name="currculumCommentVolume" value='+obj.data.currculumCommentVolume+'></div>');
                        boby.find("td[name = curriculumSynopsis]").html('<div><input type="text" name="curriculumSynopsis" value='+obj.data.curriculumSynopsis+'></div>');
                        boby.find("div[name = curriculumPictureurl]").html('<img src="'+obj.data.curriculumPictureurl+'", ' +
                            'style="width: 200px;height: 100px">');
                        boby.find("div[name = curriculumUrl]").html('<video controls="controls" src="'+obj.data.curriculumUrl+'" name="curriculumUrl" width="100%"></video>');
                        boby.find("input[name = videoDuration]").val(obj.data.curriculumDuration);


                    }
                })
                break;
        };
    });

});
function dropdw(){
    var data
    $.ajax({
        url : "/curriculum/primary/getAllDropDownBox",
        dataType : 'json',
        async:false,
        type : 'get',
        data :[],
        success : function(res) {
             data = res.data;
        }
    })
    return data;
}
layui.use('dropdown', function(){
    var dropdown = layui.dropdown
    let dropdw1 = dropdw();

    dropdown.render({
        elem: '#demo1' //可绑定在任意元素中，此处以上述按钮为例
        ,data: dropdw1
        ,id: 'demo1'
        //菜单被点击的事件
        ,click: function(obj){

            curriculumClassificationid = obj.id
            table.reload('curriculum',{

                where:{
                    curriculumClassificationid:curriculumClassificationid
                }
            })
        }
    });
});
var event1=null;
var treeId1 =null;
var treeNode1 = null;
function OnRightClick(event, treeId, treeNode) {
    event1 = event;
    treeId1 = treeId;
    treeNode1 = treeNode;
    if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
        zTree.cancelSelectedNode();
        showRMenu("root", event.clientX, event.clientY);
    } else if (treeNode && !treeNode.noR) {
        zTree.selectNode(treeNode);
        showRMenu("node", event.clientX, event.clientY);
    }
}

function showRMenu(type, x, y) {
    $("#rMenu ul").show();
    if (type=="root") {
        $("#m_del").hide();
        $("#m_check").hide();
        $("#m_unCheck").hide();
    } else {
        $("#m_del").show();
        $("#m_check").show();
        $("#m_unCheck").show();
    }

    y += document.body.scrollTop;
    x += document.body.scrollLeft;
    rMenu.css({"top":y+"px", "left":x+"px", "visibility":"visible"});

    $("body").bind("mousedown", onBodyMouseDown);
}
function hideRMenu() {
    if (rMenu) rMenu.css({"visibility": "hidden"});
    $("body").unbind("mousedown", onBodyMouseDown);
}
function onBodyMouseDown(event){
    if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length>0)) {
        rMenu.css({"visibility" : "hidden"});
    }
}
var addCount = 1;
var uname = localStorage.getItem("uname");
function addTreeNode() {
    $.ajax({
        url : "/curriculum/sort/intermediate/add",
        dataType : 'json',
        type : 'post',
        data :{"classificationPid":treeNode1.classificationId,"classificationName":"新课程","classificationCreatedBy":uname},
        success : function(response) {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            console.log(response)
            zTree.addNodes(treeNode1, response);
            hideRMenu();
            log("添加课程分类")
        },
        errorfun : function() {
            ws.tools.modalDialog.alert('请求失败！',2);
        }
    });

}
function removeTreeNode() {

    if(treeNode1.classificationPid==0){                //如果删除的是根节点，也提示无法删除
        alert("根节点无法删除！")
        return false;                    //返回false 就会使前端的节点还保持存在，
        //	如果是true,则会在前端界面删除，但数据库中还会有，刷新一下即可再次出现
    }
    if(confirm("是否删除？")){  // 询问是否删除，若删除，则利用Ajax 技术异步删除，同是返回json格式数据，告知前台是否删除成功！
        $.ajax({
            url : "/curriculum/sort/intermediate/del",
            dataType : 'json',
            type : 'post',
            data :{"classificationId":treeNode1.classificationId},
            success : function(response) {
                zTree.removeNode(treeNode1);     // z-Tree 的api ，从视角上 删除
                alert(response.msg);
                hideRMenu();
                log("删除课程分类")
            },
            error : function(response) {
                alert(response.msg);
                return false;
                hideRMenu();
            }
        });
    }
    return ;
}
var log, className = "dark";
function checkTreeNode() {
    className = (className === "dark" ? "":"dark");
    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
    zTree.selectNode(treeNode1);
    setTimeout(function() {
        setTimeout(function() {
            zTree.editName(treeNode1);
        }, 0);
    }, 0);
    hideRMenu();
    return false;

}
function resetTree() {
    hideRMenu();
    $.fn.zTree.init($("#treeDemo"), setting, zNodes);
}

var zTree, rMenu;
//右键树结构
function zTreeOnRightClick(event, treeId, treeNode) {
    // console.log(treeNode);
    $("#fileNode_pid").val(treeNode.id);
    $("#fileNode_pname").val(treeNode.damc);
    if (!treeNode && event.target.tagName.toLowerCase() != "button" && $(event.target).parents("a").length == 0) {
        showRMenu("root", event.clientX, event.clientY);
    } else if (treeNode && !treeNode.noR) {
        showRMenu("node", event.clientX, event.clientY);
    }
};

//显示右键菜单
function showRMenu(type, x, y) {
    $("#rMenu").show();
    $("#rMenu").css({"top": y + "px", "left": x + "px", "visibility": "visible"}); //设置右键菜单的位置、可见
    $("body").bind("mousedown", onBodyMouseDown);
}

//隐藏右键菜单
function hideRMenu() {
    $("#rMenu").css({"visibility": "hidden"}); //设置右键菜单不可见
    $("body").unbind("mousedown", onBodyMouseDown);
}
//鼠标按下事件
function onBodyMouseDown(event) {
    if (!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
        // $("#rMenu").hide();
        $("#rMenu").css({ "visibility": "hidden"});
    }
}


function beforeRename(treeId, treeNode, newName, isCancel) {
    if (newName.length == 0) {
        setTimeout(function() {
            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            zTree.cancelEditName();
            alert('名称不能为空！');
        }, 0);
        return false;
    }else{
        $.ajax({
            url : "/curriculum/sort/intermediate/update",
            dataType : 'json',
            type : 'post',
            data :{"classificationId":treeNode1.classificationId,"classificationName":newName,"classificationUpdatedBy":uname},
            success : function(response) {
                log("修改分类名称")
            },
            error : function() {
                ws.tools.modalDialog.alert('请求失败！',2);
            }
        });
    }
    return true;
}
var settingss = {
    view: {
        dblClickExpand: false
    },
    callback: {
        onRightClick: OnRightClick,
        beforeRename: beforeRename,
        onCheck: zTreeOnCheck,
        onClick: zTreeOnClick

    },
    data: {
        simpleData: {
            enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
            idKey: "classificationId",   //节点数据中保存唯一标识的属性名称
            pIdKey: "classificationPid",    //节点数据中保存其父节点唯一标识的属性名称
            rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
        },
        key: {
            name: "classificationName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
        }
    },
    check:{
        enable:true,  //true 、 false 分别表示 显示 、不显示 复选框或单选框
        nocheckInherit:true,   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        chkboxType:{//复选框树形菜单勾选父节点，子节点全部勾选。子节点勾选，父节点不勾选
            "Y":"s",
            "N":"ps"
        }
    }
};
var zTree, rMenu;
$(document).ready(function(){
    $.ajax({
        type:"get",
        url:"/curriculum/sort/primary/getAll",
        async:true,
        success:function(res){
            console.log(res)
            zTree = $.fn.zTree.init($("#treeDemo"), settingss, res.data); //初始化树
            zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            rMenu = $("#rMenu");
        }
    });
});